package com.bpzj.util.log;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.classic.spi.Configurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.spi.ContextAwareBase;
import java.net.URL;
import org.slf4j.helpers.Util;

public class LogbackConfiguration extends ContextAwareBase implements Configurator {
  // TODO http://logback.qos.ch/manual/configuration.html
  // 通过 spi 使用 java类来配置 logback
  // jvm -D 参数 开启或关闭日志

  @Override
  public void configure(LoggerContext loggerContext) {
    this.addInfo("Setting up retail default configuration.");
    // 清除loggerContext已加载配置，重新加载
    loggerContext.reset();
    JoranConfigurator configurator = new JoranConfigurator();
    try {
      //  获取jar中默认配置文件路径
      URL url = Configurator.class.getClassLoader().getResource("logback-default.xml");
      // 设置loggerContext到JoranConfigurator
      configurator.setContext(loggerContext);
      // 加载默认配置
      configurator.doConfigure(url);

      // 解决 SpringBoot 项目， 此配置文件不生效的问题
      try {
        Class<?> aClass = Class.forName(" org.springframework.boot.logging.LoggingSystem");
        loggerContext.putObject(aClass.getName(), 1);
      } catch (ClassNotFoundException e) {
        this.addInfo("No spring boot application");
      }

    } catch (JoranException e) {
      Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", e);
    }
  }

}
